package com.yulebaby.callsenter.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.SelectRecordAdapter;
import com.yulebaby.callsenter.bean.CallLogBean;
import com.yulebaby.callsenter.database.manager.Dao;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.ui.base.BaseActivity;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.MediaPlayerUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 售前回访记录activity
 *
 * @author zhangbo
 * @date 2017-1-12.
 */

public class ShowReturnRecordActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, MediaPlayerUtils.CompletionListener {


    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.tv_save)
    TextView mTvSave;
    @BindView(R.id.rv_recod)
    RecyclerView mRvRecod;
    @BindView(R.id.sr_refresh)
    SwipeRefreshLayout mSrRefresh;

    private List<CallLogBean> callLogList;


    private MediaPlayerUtils mPlayerUtils;

    private int lastPosition = -1;

    private CallLogBean mClickCallLogBean;

    private boolean isRefresh;

    //记录选择的Item
    private LinkedList<CallLogBean> positionList;

    private SelectRecordAdapter mCallLogAdapter;
    private ArrayList<Long> mCallTime;
    private int CAN_SELECTED_RECORD_COUNT = 3;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_return_record;
    }

    @Override
    protected void initView() {
        initRefresh();
    }

    @Override
    protected void initData() {

        Intent intent = getIntent();
        mCallTime = (ArrayList<Long>) intent.getSerializableExtra(Constant.CALL_TIME); //取数据
        positionList = new LinkedList<>();
        callLogList = new ArrayList<>();
        mRvRecod.setHasFixedSize(true);
        mRvRecod.setLayoutManager(new YuLeBaByLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mCallLogAdapter = new SelectRecordAdapter(callLogList);
        mPlayerUtils = MediaPlayerUtils.getInstances();
        mPlayerUtils.setOnCompletionListener(this); //初始化播放
        mRvRecod.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mClickCallLogBean = (CallLogBean) baseQuickAdapter.getItem(position);

                if (lastPosition != position) {
                    if (mPlayerUtils.isPlaying() && lastPosition != -1) {
                        mPlayerUtils.pause();
                        (((CallLogBean) baseQuickAdapter.getItem(lastPosition))).setPlayState(2);
                        mCallLogAdapter.notifyDataSetChanged();
                    }
                    lastPosition = position;
                }

                switch (view.getId()) {
                    case R.id.iv_play:
                        switch (mClickCallLogBean.getPlayState()) {
                            case 0:
                                ToastUtil.showToast("没有录音文件");
                                break;
                            case 1:
                                mPlayerUtils.pause();
                                mClickCallLogBean.setPlayState(2);
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                            case 2:
                                mClickCallLogBean.setPlayState(1);
                                String file_path = mClickCallLogBean.getFile_path();
                                if (file_path.startsWith("http://")) {
                                    mPlayerUtils.openAudio(Uri.parse(file_path));
                                } else {
                                    mPlayerUtils.openAudio(file_path);
                                }
                                mCallLogAdapter.notifyDataSetChanged();
                                break;
                        }
                        break;
                    case R.id.iv_state:
                        switch (mClickCallLogBean.getSelectedState()) {
                            case 0:
                                if (positionList.size() >= CAN_SELECTED_RECORD_COUNT) {
                                    ToastUtil.showToast("最多支持上传3条录音文件");
                                } else {
                                    mClickCallLogBean.setSelectedState(1);
                                    baseQuickAdapter.notifyItemChanged(position);
                                    positionList.add(mClickCallLogBean);
                                }
                                break;
                            case 1:
                                mClickCallLogBean.setSelectedState(0);
                                baseQuickAdapter.notifyItemChanged(position);
                                positionList.remove(mClickCallLogBean);
                                break;
                            case 2:
                                ToastUtil.showToast("您已经选择此条录音");
                                break;
                        }
                        break;
                }
            }
        });
        mRvRecod.setAdapter(mCallLogAdapter);
        requestData();
    }

    /**
     * 请求数据
     */
    private void requestData() {
        Observable.create(new Observable.OnSubscribe<List<CallLogBean>>() {
            @Override
            public void call(Subscriber<? super List<CallLogBean>> subscriber) {
                List<CallLogBean> callLogBeen = Dao.getInstance().listCallLogDesHavePath();
                subscriber.onNext(callLogBeen);
            }
        }).doOnNext(callLogBeen -> {
            if (mCallTime != null) {
                for (long time : mCallTime) {
                    for (CallLogBean logBean : callLogBeen) {
                        if (logBean.getCall_time() == time) {
                            logBean.setSelectedState(2);
                            CAN_SELECTED_RECORD_COUNT--;
                        }
                    }
                }
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(callLogBeen -> {
                    callLogList.clear();
                    callLogList.addAll(callLogBeen);
                    mCallLogAdapter.notifyDataSetChanged();
                    if (isRefreshing()) {
                        refreshComplete();
                    }
                });
    }


    //下拉刷新
    private void initRefresh() {
        mSrRefresh.setOnRefreshListener(this);
        mSrRefresh.setColorSchemeResources(R.color.swiperefresh_color1, R.color.swiperefresh_color2,
                R.color.swiperefresh_color3, R.color.swiperefresh_color4);
    }

    protected boolean isRefreshing() {
        return isRefresh;
    }

    protected void refreshComplete() {
        mSrRefresh.setRefreshing(false);
        isRefresh = false;
    }

    @Override
    public void onRefresh() {
        mSrRefresh.setRefreshing(true);
        isRefresh = true;
        requestData();
    }

    @Override
    public void Completion() {
        mClickCallLogBean.setPlayState(2);
        mCallLogAdapter.notifyDataSetChanged();
    }


    @OnClick({R.id.iv_back, R.id.tv_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_save:
                Intent intent = new Intent();
                intent.putExtra(Constant.SELECED_RECORD, positionList);
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }
}
